package com.zy.reggie.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zy.reggie.common.CustomException;
import com.zy.reggie.dto.SetmealDto;
import com.zy.reggie.entity.Setmeal;
import com.zy.reggie.entity.SetmealDish;
import com.zy.reggie.mapper.SetmealMapper;
import com.zy.reggie.service.SetmealDishService;
import com.zy.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 新增套餐，同时需要保存套餐和菜品的关联关系
     *
     * @param setmealDto
     */
    @Transactional
    @Override
    public void saveWithDish(SetmealDto setmealDto) {
        //将数据保存到setMeal中
        this.save(setmealDto);
        //将数据保存到setmeal_dish表中
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes = setmealDishes.stream().map((item) -> {
            //赋值ID
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(setmealDishes);

    }

    /**
     * 删除套餐，同时删除套餐和菜品的关联关系
     * @param ids
     */
    @Transactional//多表操作，保持事物的一致性
    @Override
    public void removeWithDish(List<Long> ids) {
        //先删除Setmeal表
        LambdaQueryWrapper<Setmeal> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.in(Setmeal::getId, ids);
        lambdaQueryWrapper.eq(Setmeal::getStatus, "1");
        //此时已经知道在售的套餐
        int count = this.count(lambdaQueryWrapper);
        if (count > 0) {
            //有套餐处于在售状态，不能被删除
            //直接抛异常-自定义的异常
            throw new CustomException("该套餐处于在售状态，无法删除!");
        }
            this.removeByIds(ids);
        //删除setmeal_dish表
        LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealDishLambdaQueryWrapper.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(setmealDishLambdaQueryWrapper);
    }
}
